"""
核心接口定义模块

定义系统各组件的抽象接口，实现依赖注入和组件解耦
"""

from abc import ABC, abstractmethod
from typing import Dict, List, Any, Optional, Union, Callable
from datetime import datetime
import asyncio


class IDataProvider(ABC):
    """数据提供者接口"""
    
    @abstractmethod
    async def get_kline_data(self, symbol: str, interval: str, 
                           start_time: Optional[datetime] = None,
                           end_time: Optional[datetime] = None,
                           limit: int = 500) -> List[Dict[str, Any]]:
        """获取K线数据"""
        pass
    
    @abstractmethod
    async def get_ticker_data(self, symbol: str) -> Dict[str, Any]:
        """获取实时价格数据"""
        pass
    
    @abstractmethod
    async def subscribe_market_data(self, symbols: List[str], 
                                  callback: callable) -> None:
        """订阅市场数据"""
        pass


class IDataStorage(ABC):
    """数据存储接口"""
    
    @abstractmethod
    async def save_kline_data(self, exchange: str, symbol: str, 
                            interval: str, data: List[Dict[str, Any]]) -> bool:
        """保存K线数据"""
        pass
    
    @abstractmethod
    async def load_kline_data(self, exchange: str, symbol: str, 
                            interval: str, start_time: Optional[datetime] = None,
                            end_time: Optional[datetime] = None) -> List[Dict[str, Any]]:
        """加载K线数据"""
        pass
    
    @abstractmethod
    async def get_data_info(self, exchange: str, symbol: str, 
                          interval: str) -> Dict[str, Any]:
        """获取数据信息"""
        pass


class IExchangeAdapter(ABC):
    """交易所适配器接口"""
    
    @abstractmethod
    async def connect(self) -> bool:
        """连接交易所"""
        pass
    
    @abstractmethod
    async def get_account_balance(self, account_type: str = "spot") -> Dict[str, Any]:
        """获取账户余额"""
        pass
    
    @abstractmethod
    async def place_order(self, symbol: str, side: str, order_type: str,
                        amount: float, price: Optional[float] = None,
                        **kwargs) -> Dict[str, Any]:
        """下单"""
        pass
    
    @abstractmethod
    async def cancel_order(self, symbol: str, order_id: str) -> Dict[str, Any]:
        """撤单"""
        pass
    
    @abstractmethod
    async def get_order_status(self, symbol: str, order_id: str) -> Dict[str, Any]:
        """获取订单状态"""
        pass


class IStrategy(ABC):
    """策略接口"""
    
    @abstractmethod
    async def initialize(self, config: Dict[str, Any]) -> None:
        """初始化策略"""
        pass
    
    @abstractmethod
    async def on_market_data(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
        """处理市场数据，返回交易信号"""
        pass
    
    @abstractmethod
    async def on_order_update(self, order: Dict[str, Any]) -> None:
        """处理订单更新"""
        pass
    
    @abstractmethod
    async def get_strategy_status(self) -> Dict[str, Any]:
        """获取策略状态"""
        pass
    
    @abstractmethod
    async def stop(self) -> None:
        """停止策略"""
        pass


class IRiskManager(ABC):
    """风险管理接口"""
    
    @abstractmethod
    async def validate_order(self, order: Dict[str, Any], 
                           account_info: Dict[str, Any]) -> Dict[str, Any]:
        """验证订单风险"""
        pass
    
    @abstractmethod
    async def check_position_risk(self, positions: List[Dict[str, Any]]) -> Dict[str, Any]:
        """检查仓位风险"""
        pass
    
    @abstractmethod
    async def get_risk_metrics(self) -> Dict[str, Any]:
        """获取风险指标"""
        pass


class IOrderManager(ABC):
    """订单管理接口"""
    
    @abstractmethod
    async def submit_order(self, order: Dict[str, Any]) -> str:
        """提交订单"""
        pass
    
    @abstractmethod
    async def cancel_order(self, order_id: str) -> bool:
        """取消订单"""
        pass
    
    @abstractmethod
    async def get_order_history(self, symbol: Optional[str] = None,
                              start_time: Optional[datetime] = None,
                              end_time: Optional[datetime] = None) -> List[Dict[str, Any]]:
        """获取订单历史"""
        pass
    
    @abstractmethod
    async def get_active_orders(self, symbol: Optional[str] = None) -> List[Dict[str, Any]]:
        """获取活跃订单"""
        pass


class IAccountManager(ABC):
    """账户管理接口"""
    
    @abstractmethod
    async def get_account_summary(self) -> Dict[str, Any]:
        """获取账户摘要"""
        pass
    
    @abstractmethod
    async def get_positions(self, symbol: Optional[str] = None) -> List[Dict[str, Any]]:
        """获取持仓信息"""
        pass
    
    @abstractmethod
    async def update_account_info(self) -> None:
        """更新账户信息"""
        pass


class IPerformanceMonitor(ABC):
    """性能监控接口"""
    
    @abstractmethod
    async def start_monitoring(self, interval: float = 5.0) -> None:
        """开始性能监控"""
        pass
    
    @abstractmethod
    async def stop_monitoring(self) -> None:
        """停止性能监控"""
        pass
    
    @abstractmethod
    async def record_metric(self, name: str, value: float, unit: str,
                          tags: Optional[Dict[str, str]] = None) -> None:
        """记录性能指标"""
        pass
    
    @abstractmethod
    def timer(self, name: str):
        """创建性能计时器"""
        pass


class IEventBus(ABC):
    """事件总线接口"""
    
    @abstractmethod
    async def publish(self, event_type: str, data: Dict[str, Any], 
                     source: Optional[str] = None) -> None:
        """发布事件"""
        pass
    
    @abstractmethod
    async def subscribe(self, event_type: str, handler: Callable,
                       priority: int = 0) -> str:
        """订阅事件"""
        pass
    
    @abstractmethod
    async def unsubscribe(self, subscription_id: str) -> None:
        """取消订阅"""
        pass


class ISecurityManager(ABC):
    """安全管理接口"""
    
    @abstractmethod
    async def encrypt_data(self, data: str) -> str:
        """加密数据"""
        pass
    
    @abstractmethod
    async def decrypt_data(self, encrypted_data: str) -> str:
        """解密数据"""
        pass
    
    @abstractmethod
    async def generate_access_token(self, user_id: str, permissions: List[str],
                                  expires_in: int = 3600) -> str:
        """生成访问令牌"""
        pass
    
    @abstractmethod
    async def validate_access_token(self, token: str) -> Dict[str, Any]:
        """验证访问令牌"""
        pass